package com.lagou.zerocopy;

import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NioServerSocket {

    public static void main(String[] args) throws Exception {
        ServerSocketChannel open = ServerSocketChannel.open();
        open.bind(new InetSocketAddress(6689));

        while (true) {
            SocketChannel accept = open.accept();

            String fileName = "Python-2.7-" + System.currentTimeMillis() + ".tgz";
//            String fileName = "file-" + System.currentTimeMillis() + ".txt";

            FileOutputStream outputStream = new FileOutputStream(fileName);

            FileChannel outputStreamChannel = outputStream.getChannel();

            ByteBuffer allocate = ByteBuffer.allocate(1024 * 1024);

            long startTime = System.currentTimeMillis();
            int total = 0;
            int read = 0;
            while ((read = accept.read(allocate))> 0) {
                allocate.flip();
                outputStreamChannel.write(allocate);
                total += read;
                allocate.rewind();
            }

            long endTime = System.currentTimeMillis();

            System.out.println("服务端用时：" + (endTime - startTime) + ", 文件字节长度为： " + total);

            outputStreamChannel.close();
            accept.close();
            outputStream.close();
        }

    }
}
